package ua.exchangeratesukraine.ui.fragment;

import java.util.ArrayList;
import java.util.Date;
import java.util.Map.Entry;

import ua.exchangeratesukraine.R;
import ua.exchangeratesukraine.actions.DataTask;
import ua.exchangeratesukraine.actions.WorkDB;
import ua.exchangeratesukraine.adapter.NbuAdapter;
import ua.exchangeratesukraine.model.CurrencyModel;
import ua.exchangeratesukraine.util.Constants;
import ua.exchangeratesukraine.util.Util;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class FragmentNbu extends FragmentBase {

	private String	URL_NBU		= "";
	private String	tableName	= Constants.TABLE_NAME_NBU;
	
	@Override
	public void onAttach(Activity activity) {
		wdb = new WorkDB();
		wdb.createDB(getActivity());
		wdb.createTable(tableName);
		super.onAttach(activity);
	}
	
	@SuppressLint("InflateParams")
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle inState) {
		
		View view = inflater.inflate(R.layout.fragment_nbu, null);

		listHeader = inflater.inflate(R.layout.list_header_nbu, null);
		listFooter = inflater.inflate(R.layout.list_footer, null);
		btnResult = (Button) view.findViewById(R.id.btnResult);
		tvDate = (TextView) view.findViewById(R.id.tvDate);
		tvCurrentDate = (TextView) view.findViewById(R.id.tvCurrentDate);
		bar = (ProgressBar) view.findViewById(R.id.progressBar);
		bar.setVisibility(View.INVISIBLE);
		btnResult.setOnClickListener(this);
		btnResult.setOnTouchListener(this);
		tvCurrentDate.setOnClickListener(this);
		tvCurrentDate.setOnTouchListener(this);
		return view;
	}


	@Override
	public void onActivityCreated(Bundle inState) {
		date = getCurrentDate();
		if (inState != null) {
			
			isRotate = true;
			date = inState.getString(Constants.DATE);
			prevDate = inState.getString(Constants.PREV_DATE);
			isListShow = inState.getBoolean(Constants.IS_LIST_SHOW);
			currencyModelArray = inState.getParcelableArrayList(Constants.CURRENCY_MODEL_ARRAY);

			if ( isListShow && !currencyModelArray.isEmpty() && !hasHeader) {
				getListView().addHeaderView(listHeader);
				getListView().addFooterView(listFooter);
			}

			if (adapter == null) {
				adapter = getAdapter();
			}

			setListAdapter(adapter);
			fillTvDate(" " + getString(R.string.text_on_date) + " " + prevDate);
		}
		
		fillTvCurrentDate(date);
		String[] currencyNames = getActivity().getResources().getStringArray(R.array.currency_names);
		String[] currencyCodes = getActivity().getResources().getStringArray(R.array.currency_codes);
		for (int i = 0; i < currencyCodes.length; i++) {
			currency.put(currencyCodes[i], currencyNames[i]);
		}
		super.onActivityCreated(inState);
	}

	@Override
	public void onClick(View v) {

		currentTime = (new Date()).getTime();
		if( (currentTime - prevTime) < 700 )
			return;

		switch (v.getId()) {
			case R.id.tvCurrentDate:
				showDateDialog();
				break;
			case R.id.btnResult:
				
				if(checkDate())
					return;
				
				fillTvCurrentDate(date);
				
				Object response = null;
				response = wdb.read(date, tableName, "");
				if (!response.getClass().equals(Boolean.class)) {
					state	= Constants.STATE_FROM_DB;
					setData(response, null, state);
				} else {
					isNetworkAvailable = Util.isNetworkAvailable(context);
					if (!isNetworkAvailable) {
						showToast(getString(R.string.title_toast_connection_error),
									getString(R.string.text_toast_connection_error), 2);
						return;
					}
					// get data from server
					toServer(wdb);
				}
				break;
			default:
				break;
		}
		prevTime = currentTime;
	}

	public void toServer(WorkDB wdb) {
		URL_NBU = BASE_URL + "/kursy-valut/nbu_xml/?id=" + WEB_ID + "&date=" + date;
		fillTvCurrentDate(date);
		DataTask mTask = new DataTask(context, this, wdb);
		mTask.execute(URL_NBU, date, tableName);
	}
	
	protected NbuAdapter getAdapter() {
		return new NbuAdapter(context, currencyModelArray);
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {

		outState.putBoolean(Constants.IS_LIST_SHOW, isListShow);
		outState.putString(Constants.DATE, date);
		outState.putString(Constants.PREV_DATE, prevDate);
		outState.putParcelableArrayList(Constants.CURRENCY_MODEL_ARRAY, currencyModelArray);
		super.onSaveInstanceState(outState);
	}
	
	@Override
	public void sortFragment(View view, boolean isFirstRequest) {
		sort(view,  isFirstRequest);
		initArray();
	}

	public void sort(final View view, boolean isRequest) {
		currencyModelArray = Util.sortNBU(view, currencyModelArray, isRequest);
	}

	@Override
	protected void setCurrencyName(ArrayList<CurrencyModel> currencyModelArray) {
		for (CurrencyModel currencyModel : currencyModelArray) {
			for (Entry<String, String> cur : currency.entrySet()) {
				if(currencyModel.getCode().equals(cur.getKey()))
					currencyModel.setName(cur.getValue());
			}
		}
	}

	@Override
	public String getTableName(){
		return tableName;
	}
}